<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div>
        <!-- 搜索框区域 -->
        <div style="margin-top: 15px">
          <el-row :gutter="20">
            <el-col :span="7">
              <el-input
                placeholder="请输入内容"
                v-model="queryInfo.query"
                clearable
                @clear="getUserList"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="getUserList"
                ></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="dialogVisible = true">
                添加用户
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 用户列表区域 -->
        <el-table :data="users" style="width: 100%" border stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="180">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="180">
          </el-table-column>
          <el-table-column label="状态" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="changeState(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editUser(scope.row.id)"
              ></el-button>
              <!-- 删除 -->
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeUserById(scope.row.id)"
              ></el-button>
              <!-- 分配角色 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-setting"
                  @click="editRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 导航栏 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 点击添加按钮弹出来的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <!-- 手机 -->
        <el-form-item label="电话号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="validAddUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogVisibleClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 控制角色分配的对话框 -->
    <el-dialog
      title="角色分配"
      :visible.sync="roleDialogVisible"
      width="30%"
      @close="setRoleDialogClose"
    >
      <div>
        <p>当前姓名:{{ roleInfo.username }}</p>
        <p>当前角色:{{ roleInfo.role_name }}</p>
        <p>
          分配角色:
          <el-select v-model="selectRole" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    //自定义验证邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail =
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (regEmail.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱'))
      }
    }
    //自定义验证手机
    var checkPhone = (rule, value, callback) => {
      const regPhone =
        /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      if (regPhone.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      queryInfo: {
        query: '',
        //当前页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 2,
      },
      total: 0,
      users: [],
      //控制对话框的显示和隐藏
      dialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //修改查询到的用户信息
      editForm: [],
      addRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 10,
            max: 15,
            message: '长度在 10 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      //控制分配角色的弹出
      roleDialogVisible: false,
      //传递过来的当前的角色分配行信息
      roleInfo: {},
      //所有用户列表信息
      roleList: [],
      //用于保存分配完成的角色 是id 而不是name
      selectRole: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.total = res.data.total
      this.users = res.data.users
      console.log(res)
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听 pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    async changeState(stateInfo) {
      console.log(stateInfo)
      const { data: res } = await this.$http.put(
        `users/${stateInfo.id}/state/${stateInfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        stateInfo.mg_state = !stateInfo.mg_state
        return this.$message.error('请求失败')
      }
      this.$message.success('修改成功')
    },
    //重置表单的实现
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    validAddUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        //执行添加
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        } else {
          this.$message.success('添加成功')
          this.dialogVisible = false
          this.getUserList()
        }
      })
    },
    //修改用户
    async editUser(id) {
      // console.log(id);
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('错误')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //关闭对话框重置修改用户信息
    editDialogVisibleClose() {
      this.$refs.editFormRef.resetFields()
    },
    //对提交表单前的预校验
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return
        //发起网络请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('用户更新数据失败')
        }
        //关闭对话框
        this.editDialogVisible = false
        //更新数据
        this.getUserList()
        //提示修改成功
        this.$message.success('用户更新数据成功')
      })
      //  const va = await this.$refs.editFormRef.validate()
      //  console.log(va);
    },
    //删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户确认了删除 返回值为字符串 confirm
      //如果小区了删除返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('以消除删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    //分配角色
    async editRole(roleInfo) {
      this.roleInfo = roleInfo
      //获取所有用户角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户角色列表失败')
      }
      this.roleList = res.data
      console.log(this.roleList)
      this.roleDialogVisible = true
    },
    async saveRoleInfo() {
      if (!this.selectRole) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.roleInfo.id}/role`,
        {
          rid: this.selectRole,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.getUserList()
      this.$message.success('分配角色成功')
      this.roleDialogVisible = false
    },
    //监听对话框关闭后
    setRoleDialogClose(){
      this.selectRole = ''
      this.roleInfo = []
    }
  },
}
</script>

<style>
</style>